# -*- coding: cp866 -*-

import MSLogger
from datetime import timedelta, datetime
from time import time

TIME_FORMAT_MAGIC = '%d%m%Y_%H%M%S'     #time format descriptor used in magic api
TIME_FORMAT_MAGICDB = '%Y-%m-%d %H:%M:%S'
TIME_FORMAT_PCN = '%Y-%m-%d %H:%M:%S'   #time format descriptor used in pcn db
TIME_FORMAT_CESAR = '%d.%m.%Y %H:%M:%S'
MS_MSGID_TO_CONTACTID = {
    '13':'1103',
    '22':'1101',
	'28':'3011',
	'27':'3013',
    '21':'1137',
    '12':'3137'
}
#2Jeka: 28,27 nnado?
MS_MSGID_TO_CONTACTID_INPUT1 = {
    '11':'1103',
    '13':'1103',
    '20':'1101',
    '22':'1101',
    '28':'3011',
	'27':'3013',
    '30':'3021',
	'29':'3023',
    '12':'1391',
    '21':'1393'
}
#MS_MSGID_TO_CONTACTID = {}
#MS_MSGID_TO_CONTACTID_INPUT1 = {}
MS_BOLID_TO_CONTACTID = {
    'ВЗЛОМКОРПУСА':'3831',
    'ВОССТ.КОРПУСА':'3833',
    'ПОЖ':'1101',
    'ПОЖАР':'1101',
    'СБРОСТРЕВОГИШС':'1103',
    'ВНИМАНИЕ':'1181',
    'ТРЕВОГА':'1231',
	'ТИХАЯТРЕВОГА':'1221',
	'ТРЕВОГАВХОДА':'1341',
	'ИЗМ.ДАТЫ':'6253',
	'ВЗЯТШС':'4003',
	'СНЯТШС':'4011',
	'ПРОГРАММИРОВАНИЕ':'6271',
	'СБРОСПРИБОРА':'3051',
	'ОБР':'3311',
	'КЗ':'3321',
	'АВПИТ':'3011',
	'ВОССТ':'3013',
	'ОБРЫВШС':'3311',
	'РАЗДЕЛВЗЯТ':'4023',
	'РАЗДЕЛСНЯТ':'4021',
	'КОРОТКОЕЗАМЫКАН':'3321',
	'ИДЕНТИФИКАЦИЯХО':'4221',
	'КЗВЫХОДА':'3201',
	'ОБРЫВВЫХОДА':'3201',
	'НЕИСПР.ТЕЛ.ЛИНИИ':'3501',
	'НЕИЗ.СОБЫТИЕ091':'3503',
	'ВЫКЛ.ПРИНТЕРА':'3361',
	'ВКЛ.ПРИНТЕРА':'3363',
	'ИЗМ.ВРЕМЕНИ':'6253'
}

class MSEvent:
    def __init__(self):
        #event internal identificator
        self.eventId = 0
        #event internal type
        self.eventType = 0
        #object owner of the event - who generated
        self.objectId = 0
        #user owner of the event - who this object belongs to
        self.userOwnerId = 0
        #user writer of the event - who put into DB
        self.userWriterId = 0
        #when event has been received by me
        self.eventReceiveTime = datetime.fromtimestamp(time())
        #when event has been generated
        self.eventGenerateTime = self.eventReceiveTime
        #when event has been saved by ms
        self.eventSaveTime = self.eventGenerateTime

#STATIC EVENT DATA
        #does event have static data
        self.hasStatic = False
        self.isBolid = False
        #event type in ContactId's notation
        self.contactIdType = 0
        self.contactIdFull = 0
        self.contactIdZona = 0
        self.contactIdGroup = 0

#MOBILE EVENT DATA
        #does event have gps coordinates
        self.hasMobile = False
        #TBD describe coordinate notation and speed measurements
        self.GPSLatitude = 0.0
        self.GPSLongitude = 0.0
        self.GPSSpeed = 0.0

    def __hash__(self):
        return self.eventId

    def __cmp__(self, y):
        if y == None:
            return 1
        if self.eventGenerateTime > y.eventGenerateTime:
            return 1
        if self.eventGenerateTime < y.eventGenerateTime:
            return -1
        if self.eventId > y.eventId:
            return 1
        if self.eventId < y.eventId:
            return -1
        return 0

    '''
    def fromPGSM(self, rawEvent):
        global MS_MSGID_TO_CONTACTID
        global TIME_FORMAT_MAGIC
        self.hasStatic = True
        self.contactIdType = MS_MSGID_TO_CONTACTID.get(str(rawEvent['type']), None)
        if self.contactIdType == None:
            raise Exception('unknown PGSM type %s' % (str(rawEvent['type'])))
        self.eventGenerateTime = datetime.strptime(rawEvent['datetime'], TIME_FORMAT_MAGIC)
        if rawEvent.has_key('savetime'): self.eventSaveTime = datetime.strptime(rawEvent['savetime'], TIME_FORMAT_MAGIC)
        self.contactIdZona = '099'
        self.contactIdGroup = '99'
        self.eventId = rawEvent['eventId']
        #self.eventId = rawEvent['eventInternalId']
        self.eventIdToKirill = rawEvent['eventIdToKirill']
    '''
    def fromPGSM_API(self, rawEvent):
        global MS_MSGID_TO_CONTACTID
        global TIME_FORMAT_MAGIC
        self.hasStatic = True
        self.eventGenerateTime = datetime.strptime(rawEvent['datetime'], TIME_FORMAT_MAGIC)
        if rawEvent.has_key('savetime'): self.eventSaveTime = datetime.strptime(rawEvent['savetime'], TIME_FORMAT_MAGIC)
        self.contactIdType = MS_MSGID_TO_CONTACTID.get(str(rawEvent['type']), None)
        if self.contactIdType == None:
            return False
        self.contactIdZona = '099'
        self.contactIdGroup = '00'

        contactId_EType = self.contactIdType[3]
        contactId_Type = self.contactIdType[0:3]
        contactId_Zona = '099'
        contactId_Group = '00'
        contactId_Object = str(self.objectId)
        if len(contactId_Object) == 3: contactId_Object = '0%s' % (str(contactId_Object))
        if len(contactId_Object) == 2: contactId_Object = '00%s' % (str(contactId_Object))
        if len(contactId_Object) == 1: contactId_Object = '000%s' % (str(contactId_Object))
        self.contactIdFull = '18' + contactId_Object + contactId_EType + contactId_Type + contactId_Group + contactId_Zona + '0'    
        return True

    def fromPGSM_INPUT1(self, rawEvent):
        global MS_MSGID_TO_CONTACTID
        global TIME_FORMAT_MAGIC
        self.hasStatic = True
        self.contactIdType = MS_MSGID_TO_CONTACTID_INPUT1.get(str(rawEvent['type']), None)
        if self.contactIdType == None:
            raise Exception('unknown PGSM type %s' % (str(rawEvent['type'])))
        self.eventGenerateTime = datetime.strptime(rawEvent['datetime'], TIME_FORMAT_MAGIC)
        if rawEvent.has_key('savetime'): self.eventSaveTime = datetime.strptime(rawEvent['savetime'], TIME_FORMAT_MAGIC)
        if str(rawEvent['type']) == '20': self.contactIdZona = '1970'
        elif str(rawEvent['type']) == '21': self.contactIdZona = '1980'
        elif str(rawEvent['type']) == '22': self.contactIdZona = '1990'
        elif str(rawEvent['type']) == '12': self.contactIdZona = '1980'
        else: self.contactIdZona = '9990'
        #self.contactIdZona = '9999'
        self.contactIdGroup = '099'
        self.eventId = rawEvent['eventId']
        #self.eventId = rawEvent['eventInternalId']
        self.eventIdToKirill = rawEvent['eventIdToKirill']

    def fromPGSM_AUTOTEST(self, rawEvent):
        global TIME_FORMAT_MAGIC
        self.hasStatic = True
        self.contactIdType = {'98':'6021', '41':'6021'}.get(str(rawEvent['type']), None)
        if self.contactIdType == None:
            raise Exception('unknown PGSM type %s' % (str(rawEvent['type'])))
        self.eventGenerateTime = datetime.strptime(rawEvent['datetime'], TIME_FORMAT_MAGIC)
        self.eventGenerateTime = self.eventReceiveTime
        #self.eventId = rawEvent['eventInternalId']


    def fromBolid(self, rawEvent):
        global MS_BOLID_TO_CONTACTID
        global TIME_FORMAT_MAGIC
        self.hasStatic = True

        #import pdb; pdb.set_trace()
        rawParsed   = str(rawEvent['type']).split('|')
        rawType     = rawParsed[2].replace(' ', '').decode('cp866').encode('u8')
        shleif      = rawParsed[3].replace(' ', '')
        shleif      = shleif.split('/')[1].replace(' ', '')
        razdel      = rawParsed[4].replace(' ', '')

        if len(razdel) == 0: self.contactIdGroup = '00'
        elif len(razdel) == 1: self.contactIdGroup = '0' + razdel
        else: self.contactIdGroup = razdel

        if len(shleif) == 0: self.contactIdZona = '0000'
        elif len(shleif) == 1: self.contactIdZona = '00' + shleif + '0'
        elif len(shleif) == 2: self.contactIdZona = '0' + shleif + '0'
        elif len(shleif) == 3: self.contactIdZona = shleif + '0'

        self.contactIdType = MS_BOLID_TO_CONTACTID.get(str(rawType), None)
        if self.contactIdType == None:
            raise Exception('unknown BOLID type %s' % (str(rawType)))
        self.eventGenerateTime  = datetime.strptime(rawEvent['datetime'], TIME_FORMAT_MAGIC)
        self.eventId = rawEvent['eventId']
        self.eventIdToKirill = rawEvent['eventIdToKirill']
        self.isBolid = True
        MSLogger.logInfo('DEBUG: fromBolid: "%s" "%s" -> %s %s' % (str(rawParsed[3]), str(rawParsed[4]), str(self.contactIdGroup), str(self.contactIdZona)))
        #import pdb; pdb.set_trace()
        
    def fromArgus(self, raw):
        self.hasStatic = True
        self.contactIdType = raw['type']
        self.eventGenerateTime = datetime.strptime(raw['datetime'], TIME_FORMAT_MAGIC)
        self.eventId = raw['eventId']
        self.eventIdToKirill = raw['eventId']

    def fromContactId(self, rawEvent):
        self.hasStatic = True
        cid = rawEvent['value']
        contactId_Object = cid[2:6]
        contactId_EType = cid[6:7]
        contactId_Type = cid[7:10]
        contactId_Group = cid[10:12]
        contactId_Zona = cid[12:15]
        self.contactIdFull = cid
        self.contactIdType = "%s%s" % (contactId_Type, contactId_EType)
        self.contactIdGroup = str(contactId_Group)
        self.contactIdZona = str(contactId_Zona)
        self.objectId = int(contactId_Object)
        self.eventGenerateTime = datetime.strptime(rawEvent['date'], TIME_FORMAT_MAGIC)
        self.eventId = rawEvent['eventId']
        self.eventIdToKirill = rawEvent['eventIdToKirill']

    def fromGPSPoint(self, rawEvent):
        self.hasMobile = True
        #we should transfer LAT and LON
        #LAT
        ddd = float(rawEvent['lat'])
        self.GPSLatitudeOrig = ddd
        dd = int(ddd)
        mm = int((ddd - dd)*60)
        ss = str(((ddd - dd)*60 - mm)*60)
        mm = str(mm)
        if (len(mm)) < 2:
            mm = '0%s' % (mm[0])
        dd = str(dd)
        self.GPSLatitude = dd[0:2] + mm[0:2] + '.' + ss.replace('.','')[0:5]
        #LON
        ddd = float(rawEvent['lon'])
        self.GPSLongitudeOrig = ddd
        dd = int(ddd)
        mm = int((ddd - dd)*60)
        ss = str(((ddd - dd)*60 - mm)*60)
        mm = str(mm)
        if (len(mm)) < 2:
            mm = '0%s' % (mm[0])
        dd = str(dd)
        self.GPSLongitude = dd[0:2] + mm[0:2] + '.' + ss.replace('.','')[0:5]
        self.GPSSpeed = rawEvent['speed']
        self.eventGenerateTime = datetime.strptime(rawEvent['date'], TIME_FORMAT_MAGIC)
        #self.eventId = rawEvent['eventInternalId']


class MSObject:
    def __init__(self):
        self.objectSKey = ''
        self.objectName = ''
        self.objectMSUID = 0
        self.objectMSId = 0
        self.objectPCNId= 0

        self.lastEvent_PGSM     = None
        self.lastEvent_ContactId= None
        self.lastEvent_GPS      = None
        self.lastEvent_Bolid    = None


        self.canClearPGSMEvents = False
        self.canClearContactIdEvents = False
        self.canClearBolidEvents = False

        self.eventsPGSM         = []
        self.eventsContactId    = []
        self.eventsGPS          = []
        self.eventsBolid        = []
		
        self.cameOOS = False
        self.enableOfflineCritical = False
        self.allowINPUT1 = False

    def __hash__(self):
        return self.objectMSId
